package com.atsmart.app.receiver;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.http.HttpHelper;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;
import com.atsmart.app.model.ReportHistoryInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.atsmart.log.UserLog;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;
import com.google.json.annotations.SerializedName;

/**
 * @author yhl 2013-8-8 下午5:11:26 TODO
 */

public class HistoryReceiver extends BroadcastReceiver {
	private long length = 0;

	@Override
	public void onReceive(Context context, Intent intent) {
		if ((BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance()
				.isWiFiActive()) && BizApp.getInstance().keeping == true) {
			if (BizApp.getInstance().isfinish) {
				try {
//					Log.e("HistoryReceiver", "本地上传启动");
					checkSQL();
				} catch (Exception e) {
				}
			}
		}
	}

	/** 判断上次上传是否结束，检测是否需要上传 */
	private void checkSQL() {

		new Thread() {
			public void run() {
				List<PositionShutDownInfo> repos = null;
				BizApp.getInstance().isfinish = false;// 开始本次上传
				ShutDownSqlHelper psql = new ShutDownSqlHelper();
				psql.open(BizApp.getInstance().getSqlHelper());
				// 汇报失败手动保存sql
				try {
					repos = psql.getAttributePosLit();
				} catch (Exception e) {
				}
//				 Log.e("sql大小", "大小： = " + repos.size());
				if(BizApp.isWrite){
					UserLog.getInstance().writeSqlFile("本地sql： = " + repos.size());
				}
				
				if (repos != null && repos.size() > 0) {
				
					for (int i = 0; i < repos.size(); i++) {
						if(BizApp.isWrite){
							UserLog.getInstance().writeSqlFile("汇报失败sql" + "内容: = " + repos.get(i).getPos());
						}
//						Log.e("汇报失败sql", "内容: = " + repos.get(i).getPos());
						PositionShutDownInfo rep = repos.get(i);
						if (rep.getType() == 3) {
							PositonsInfo positionInfos = new Gson().fromJson(rep.getPos(), PositonsInfo.class);
							List<PositionInfo> positionInf = positionInfos.positions;
							PositionInfo positionInfo = positionInf.get(0);
							try{
//								Log.e("TAG", " 本次DATA: = " + positionInfo.date);
								if(PrefsUtils.getLastData() == null || StringUtil.isEmptyOrNull(PrefsUtils.getLastData())){
									PrefsUtils.setLastData(positionInfo.date);
									PrefsUtils.setLastType(String.valueOf(positionInfo.msgType));
								}else{
//									Log.e("TAG", "上次data： = " + PrefsUtils.getLastData());
									if(PrefsUtils.getLastData().equals(positionInfo.date) && PrefsUtils.getLastType().equals(positionInfo.msgType)){
										Log.e("TAG", "时间重复, 类型相同");
//										Log.e("TAG", "内容重复 本次内容： = " + rep.getPos() + " , 上次内容： = " + PrefsUtils.getLastData());
										try{
											psql.deleteById(rep.getId());
										}catch (Exception e) {
										}
										continue;
									}else{
									}
									if(PrefsUtils.getLastType().equals(positionInfo.msgType)){
										if(PrefsUtils.getLastType().equals("6") || PrefsUtils.getLastType().equals("7")){
//										Log.e("TAG", "内容重复 本次内容： = " + rep.getPos() + " , 上次内容： = " + PrefsUtils.getLastData());
										try{
											psql.deleteById(rep.getId());
										}catch (Exception e) {
										}
										continue;
										}
									}else{
									}
								}
//							if(PrefsUtils.getLastData() == null || StringUtil.isEmptyOrNull(PrefsUtils.getLastData())){
//								PrefsUtils.setLastData(rep.getPos());
//							}else{
//								if(PrefsUtils.getLastData().equals(rep.getPos())){
//									Log.e("TAG", "内容重复 本次内容： = " + rep.getPos() + " , 上次内容： = " + PrefsUtils.getLastData());
//									try{
//										psql.deleteById(rep.getId());
//									}catch (Exception e) {
//									}
//									continue;
//								}else{
//									Log.e("TAG", "内从不重复 本次内容： = " + rep.getPos() +" , 上次内容： = " + PrefsUtils.getLastData());
//								}
//							}
							}catch (Exception e) {
								Log.e("TAG", "检查重复异常");
							}
							// 巡检
							try {
								CheckDurationInfo info = ServiceHelper
										.getInstance()
										.postData(
												ServiceHost.reportLocationURL(),
												new Gson().toJson(body()),
												rep.getPos(),
												CheckDurationInfo.class);

								if (info.getResult() == 0) {
									try{
										PrefsUtils.setLastData(positionInfo.date);
										PrefsUtils.setLastType(String.valueOf(positionInfo.msgType));
										Log.e("本地巡检成功", "内容: = " + repos.get(i).getPos());
										if(BizApp.isWrite){
											UserLog.getInstance().writeSqlFile("本地巡检成功： = " + rep.getPos());
										}
									}catch (Exception e) {
									}
									psql.deleteById(rep.getId());
									sleep(50);
								} else {
									sleep(50);
									continue;
								}
							} catch (Exception e) {
								if(PrefsUtils.getURL().equals(StringUtil.URL1)){
									PrefsUtils.setURL(StringUtil.URL2);
								}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
									PrefsUtils.setURL(StringUtil.URL1);
								}
								if(BizApp.isWrite){
									UserLog.getInstance().writeSqlException("本地巡检上传异常： = "+e.getMessage());
								}
								try{
								  SystemClock.sleep(50);
								}catch (Exception ee) {
								}
								continue;

							}

						}
						if (rep.getType() == 8) {
							String pos = rep.getPos();
							String posp = rep.getPos();
							String imagestr = rep.getImagestr();

							// Log.e("图片路径", "图片路径： = " + imagestr);
							if (imagestr != null && !"".equals(imagestr)) {
								String[] imgstrs = imagestr.split(";");
								if (imgstrs.length > 1) {// 多张图片
									try {
										for (int j = 0; j < imgstrs.length; j++) {
											String[] str1 = imgstrs[j]
													.split(",");
											ImgPathInfo iinfo = im(str1[1]);
											if (iinfo.path == null
													|| "".equals(iinfo.path)) {
												break;
											} else {
												int c = posp
														.indexOf("\"item-id\":"
																+ str1[0]);
												if (c == -1) {
													int template = posp
															.indexOf("\"template\":[");
													posp = posp.substring(0,
															template + 12)
															+ "{\"value\":\""
															+ iinfo.path
															+ "\","
															+ "\"item-id\":"
															+ str1[0]
															+ ","
															+ "\"type_id\":4,\"ext-type\":0},"
															+ posp.substring(
																	template + 12,
																	posp.length());
													// Log.e("111 posp",
													// posp.toString());
												} else {
													posp = posp.substring(0,
															c - 2)
															+ iinfo.path
															+ posp.substring(
																	c - 2,
																	posp.length());
													// Log.e("222 posp",
													// posp.toString());
												}
											}
										}
									} catch (Exception e) {
										if(PrefsUtils.getURL().equals(StringUtil.URL1)){
											PrefsUtils.setURL(StringUtil.URL2);
										}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
											PrefsUtils.setURL(StringUtil.URL1);
										}
										Log.e("TAG", "多图异常");
										if(BizApp.isWrite){
											UserLog.getInstance().writeSqlException("本地多图上传异常： = "+e.getMessage());
										}
										try{SystemClock.sleep(50);}catch (Exception ee) {
										}
										continue;
									}
								} else {// 单张图片
									String[] imagestra = imagestr.split(",");
									try {
										ImgPathInfo iinfo = im(imagestra[1]);
										if (iinfo.path == null
												|| "".equals(iinfo.path)) {
											continue;
										} else {
											int c = posp.indexOf("\"item-id\":"
													+ imagestra[0]);
											posp = pos.substring(0, c - 2)
													+ iinfo.path
													+ pos.substring(c - 2,
															pos.length());
										}
									} catch (Exception e) {
										if(PrefsUtils.getURL().equals(StringUtil.URL1)){
											PrefsUtils.setURL(StringUtil.URL2);
										}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
											PrefsUtils.setURL(StringUtil.URL1);
										}
										Log.e("TAG", "单图异常");
										if(BizApp.isWrite){
											UserLog.getInstance().writeSqlException("本地单图上传异常： = "+e.getMessage());
										}
										try{SystemClock.sleep(50);}catch (Exception ee) {
										}
										continue;
									}

								}
							}
							// 直接汇报保存记录
							try {
//								Log.e("上传 == 8", posp.toString());
								ResultInfo result = ServiceHelper.getInstance()
										.postData(ServiceHost.upload(),
												posp.toString(),
												ResultInfo.class);
								if (result.result == 0) {
//									Log.e("上传成功", posp.toString());
									ReportHistoryInfo history = new ReportHistoryInfo();
									history.name = rep.getReportname();
									history.date = StringUtil.getReportTime();
									history.type = rep.getReporttype();
									BizApp.getInstance().getSqlHelper()
											.addHistory(history);

									psql.deleteById(rep.getId());
									sleep(50);
								} else {
									sleep(50);
									continue;
								}
							} catch (Exception e) {
								if(PrefsUtils.getURL().equals(StringUtil.URL1)){
									PrefsUtils.setURL(StringUtil.URL2);
								}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
									PrefsUtils.setURL(StringUtil.URL1);
								}
								if(BizApp.isWrite){
									UserLog.getInstance().writeSqlException("本地汇报内容上传异常： = "+e.getMessage());
								}
							 try{SystemClock.sleep(50);}catch (Exception ee) {}
								continue;
							}
						}
					}
				}
				BizApp.getInstance().isfinish = true;// 开始上传
			}
		}.start();
	}

	/** 上传图片 */
	private ImgPathInfo im(String path) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[10 * 1024];
		CommonBody body = new CommonBody();
		body.setCommand(1);
		body.setImsi(BizApp.getInstance().getIMSI());
		body.setVersion(BizApp.getInstance().getString(R.string.app_version));
		body.setFile("jpg");
		body.setBegin_index(0);
		String reqBody = new Gson().toJson(body);
		reqBody = reqBody + "\r\n\r\n";
		bos.write(reqBody.getBytes("ISO-8859-1"));
		FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
		for (int readNum; (readNum = fis.read(buf)) != -1;) {
			if (bos.toByteArray().length < 2000000) {
				bos.write(buf, 0, readNum);
				length += buf.length;
			} else {
				break;
			}
		}
		bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
		fis.close();
		return new Gson().fromJson(postOnService(bos.toByteArray()),
				ImgPathInfo.class);

	}

	private class ImgPathInfo implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 7216739021733421705L;
		/**
		 *
		 */
		@SerializedName("file")
		public String path;
	}

	protected String postOnService(byte[] bb) throws MalformedURLException,
			IOException, BizException {
		HttpHelper http = new HttpHelper(bb.length);
		http.setCONNECTION_TIMEOUT(10000);
		http.setREAD_TIMEOUT(10000);
		try {
			http.createMode().url(ServiceHost.uploadImage())
					.header("Content-Type", "charset=ISO-8859-1")
					.header("Accept-Charset", "ISO-8859-1");
			http.body(new ByteArrayInputStream(bb)).send();

		} catch (Exception ex) {
		}
		String bodyString = "";
		if (http.isSuccessful()) {
			bodyString = http.getBodyAsString();
			if (bodyString != null) {
				bodyString = bodyString.substring(
						bodyString.indexOf("\r\n\r\n"), bodyString.length());
				return bodyString;
			} else {
				return "";
			}
		} else {
			http.send();
			if (http.isSuccessful()) {
				bodyString = http.getBodyAsString();
				if (bodyString != null) {
					return bodyString;
				} else {
					return "";
				}
			}
			final int responseCode = http.getResponseCode();
			throw new BizException(responseCode);
		}
	}

	/** 返回body */
	private CommonBody body() {
		CommonBody body = new CommonBody();
		body.setCommand(2);
		body.setImsi(BizApp.getInstance().getIMSI());
		body.setVersion(BizApp.getInstance().getString(R.string.app_version));
		return body;
	}

}
